package com.hbut.friend.manager;

import com.hbut.common.core.constants.CacheConstants;
import com.hbut.common.redis.service.RedisService;
import com.hbut.friend.domain.user.User;
import com.hbut.friend.domain.user.vo.UserVO;
import com.hbut.friend.mapper.user.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Component
public class UserCacheManager {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;


    public UserVO getUserById(Long userId) {
        UserVO userVO = redisService.getCacheObject(getUserKey(userId), UserVO.class);
        if(userVO != null) {
            redisService.expire(getUserKey(userId), CacheConstants.USER_EXP, TimeUnit.MINUTES);
            return userVO;
        }
        // 缓存中没有，从数据库中查询
        User user = userMapper.selectById(userId); // 查询用户信息
        if(user == null) {
            return null;
        }
        refreshUserCache(user);
        userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    private void refreshUserCache(User user) {
        // 缓存用户信息
        redisService.setCacheObject(getUserKey(user.getUserId()), user);
        // 设置过期时间
        redisService.expire(getUserKey(user.getUserId()), CacheConstants.USER_EXP, TimeUnit.MINUTES);
    }

    private String getUserKey(Long userId) {
        return CacheConstants.USER_DETAIL + userId;
    }
}
